import { createSlice } from "@reduxjs/toolkit";

const CartSlice = createSlice({
  name: "CartSlice",
  initialState: {
    CartList: JSON.parse(localStorage.getItem("cart") || "[]"),
  },
  reducers: {
    // 加入购物车
    addCart(state, { payload }) {
      const item = state.CartList.find(
        (item: any) => item.body.product_id === payload.body.product_id
      );
      if (item) {
        item.body.count += 1;
      } else {
        state.CartList.push({
          ...payload,
          body: { ...payload.body, count: 1, checked: false },
        });
      }
      localStorage.setItem("cart", JSON.stringify(state.CartList));
    },
    // 购物车单选
    CheckCart(state, { payload }) {
      const item = state.CartList.find(
        (item: any) => item.body.product_id === payload.body.product_id
      );
      if (item) {
        item.checked = !payload.checked;
      }
      localStorage.setItem("cart", JSON.stringify(state.CartList));
    },
    // 商品数量
    CountCart(state, { payload }) {
      const item = state.CartList.find(
        (item: any) => item.body.product_id === payload.body.product_id
      );
      if (item) {
        item.count = payload.count;
      }
      localStorage.setItem("cart", JSON.stringify(state.CartList));
    },
    // 商品全选
    AllCar(state, { payload }) {
      state.CartList.forEach((item: any) => (item.checked = payload));
      localStorage.setItem("cart", JSON.stringify(state.CartList));
    },
  },
});
export const { addCart, CheckCart, CountCart, AllCar } = CartSlice.actions;
export default CartSlice.reducer;
